package com.songcha.module_mine.ui.fragment.mine

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.View.OnClickListener
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Divider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.songcha.library_base.mvvm.base.BaseRefreshMvvmFragment
import com.songcha.library_business.bean.advert.AdvertInfoBean
import com.songcha.library_business.config.FunctionConfig
import com.songcha.library_business.config.VarConfig
import com.songcha.library_business.helper.AdvertCoverHelper
import com.songcha.library_business.helper.AdvertHelper
import com.songcha.library_business.helper.UMengHelper
import com.songcha.library_business.proxy.login.IOnLoginSuccessEventListener
import com.songcha.library_business.proxy.login.LoginSuccessEvent
import com.songcha.library_business.proxy.main.MainEventProxy
import com.songcha.library_business.proxy.userinfo.UserInfoManager
import com.songcha.library_business.util.BusinessJumpUtil
import com.songcha.library_business.util.MajiaBaoUtil
import com.songcha.library_common.helper.SharedPreferenceHelper
import com.songcha.library_common.helper.ViewHelper
import com.songcha.library_common.ui.view.BottomNavigationView
import com.songcha.library_common.util.GlideUtil
import com.songcha.library_common.util.JumpUtil
import com.songcha.library_common.util.PackageUtil
import com.songcha.library_common.util.TimeUtil
import com.songcha.library_common.util.ToastUtil
import com.songcha.module_mine.R
import com.songcha.module_mine.bean.GoldExchangeVipBean
import com.songcha.module_mine.databinding.MineFragmentMineBinding
import com.songcha.module_mine.ui.activity.browse_history.BrowseHistoryActivity
import com.songcha.module_mine.ui.activity.feedback.FeedbackActivity
import com.songcha.module_mine.ui.activity.message.MessageActivity
import com.songcha.module_mine.ui.activity.setting.SettingActivity
import com.songcha.module_mine.ui.activity.userinfo.UserInfoActivity
import com.songcha.module_mine.ui.dialog.GoldExchangeDialog
import com.songcha.module_mine.ui.dialog.GoldExchangeTipDialog
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

@Route(path="/mine/MineFragment")
class MineFragment : BaseRefreshMvvmFragment<MineViewModel,MineFragmentMineBinding>(),IOnLoginSuccessEventListener,OnClickListener,BottomNavigationView.IOnBottomNavigationItemChangeListener {

    init {
        TAG=MineFragment::class.java.simpleName
    }

    private var mGoldExchangeDialog:GoldExchangeDialog?=null

    override fun getLayoutId(): Int {
        return R.layout.mine_fragment_mine
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        //val channel=PackageUtil.getUmengChannelName(requireContext())
        ViewHelper.setVisibility(FunctionConfig.IS_VIP_ENABLED,databinding.mineCclVip)
        /*if(!FunctionConfig.IS_VIP_ENABLED ){//&& (channel=="vivo" || channel=="huawei")
            databinding.mineCclVip.visibility=View.GONE
        }else{
            databinding.mineCclVip.visibility=View.VISIBLE
        }*/

        databinding.mineBtnLoginNow.setOnClickListener(this)
        databinding.mineLlUserTop.setOnClickListener(this)
        databinding.mineLlGoldExchange.setOnClickListener(this)
        databinding.mineLlMsg.setOnClickListener (this)
        databinding.mineLlBrowseHistory.setOnClickListener (this)
        databinding.mineLlSetting.setOnClickListener (this)
        databinding.mineLlFeedback.setOnClickListener (this)
        databinding.mineLlContinueRead.setOnClickListener (this)
        databinding.mineCclVip.setOnClickListener (this)


        if(FunctionConfig.IS_VIP_ENABLED){
            databinding.mineIvGoldExchange.setImageResource(R.mipmap.mine_icon_gold_exchange)
            databinding.mineTvGoldExchange.text="金币兑换"
        }else{
            databinding.mineIvGoldExchange.setImageResource(R.mipmap.mine_icon_my_bookshelf)
            databinding.mineTvGoldExchange.text="我的书架"
        }

        //showUserInfo()

        val majiaName = MajiaBaoUtil.getMajiaName()
        ViewHelper.setVisibility(majiaName == "douyue",databinding.mineLlMenu)
        ViewHelper.setVisibility(majiaName == "beike",databinding.mineCpvMenu)

        databinding.mineCpvMenu.setContent {
            BeikeMenuView()
        }

        EventBus.getDefault().register(this)

    }

    @Composable
    fun BeikeMenuView(){
        //because observeAsState has anti-shake function,so can not observe twice
        val msgCount by viewModel.messageCount.observeAsState(0)
        val showMsgTip = isShowMessageTip(msgCount)

        val list = mutableListOf<Map<String,Any>>(
            mapOf("title" to "继续阅读","resId" to R.mipmap.mine_icon_continue_read,"onClick" to {
                onContinueReadClick()
            }),
            mapOf("title" to "我的书架","resId" to R.mipmap.mine_icon_my_bookshelf,"onClick" to {
                onBookshelfOrGoldExchangeClick()
            }),
            mapOf("title" to "浏览历史","resId" to R.mipmap.mine_icon_browse_history,"onClick" to {
                onBrowseHistoryClick()
            }),
            mapOf("title" to "消息通知","resId" to R.mipmap.mine_icon_message_notify,"onClick" to {
                onNewMessageClick()
            }),
            mapOf("title" to "系统设置","resId" to R.mipmap.mine_icon_setting,"onClick" to {
                onSettingClick()
            }),
            mapOf("title" to "意见反馈","resId" to R.mipmap.mine_icon_feedback,"onClick" to {
                onFeedbackClick()
            }),

        )

        if(FunctionConfig.IS_VIP_ENABLED){
            list[1] = mapOf("title" to "金币兑换","resId" to R.mipmap.mine_icon_gold_exchange,"onClick" to {
                onBookshelfOrGoldExchangeClick()
            })
        }

        Column(
            modifier = Modifier
                .fillMaxWidth()
                .verticalScroll(rememberScrollState())
        ){
            for(i in list.indices){
                val item = list[i]

                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(52.dp)
                        .clickable {
                            (item["onClick"] as () -> Unit)()
                        },
                    verticalAlignment = Alignment.CenterVertically
                ){
                    Spacer(modifier = Modifier.width(21.dp))
                    Box{
                        Image(
                            modifier = Modifier.size(38.dp),
                            painter = painterResource(id = item["resId"] as Int),
                            contentDescription = null,
                            contentScale = ContentScale.Crop
                        )
                        if(i == 3 && showMsgTip)
                            Box(
                                modifier = Modifier
                                    .align(alignment = Alignment.TopEnd)
                                    .padding(0.dp, 6.dp, 6.dp, 0.dp)
                                    .size(5.dp)
                                    .clip(RoundedCornerShape(2.5.dp))
                                    .background(color = Color(0xFFFA4A5E))
                            )
                    }

                    Spacer(modifier = Modifier.width(10.dp))
                    Text(
                        text = "${item["title"]}",
                        fontSize = 12.sp,
                        color = colorResource(id = com.songcha.library_common.R.color.text_color)
                    )
                }

                if(i<list.size-1)
                    Divider(
                        thickness = 0.5.dp,
                        color = Color(0xFFF1F5F7)
                    )
            }

        }

    }

    override fun initObserver() {
        viewModel.messageCount.observe(this){data->
            showMessageTip(data)
            //update userinfo incidentally
            showUserInfo()
            databinding.mineCpvMenu.setContent {
                BeikeMenuView()
            }
        }

        viewModel.goldExchangeVipList.observe(this){data->
            hideLoadingDialog()
            showGoldExchangeDialog(data)
        }

        viewModel.goldExchangeState.observe(this){data->
            if(data){
                if(viewModel.currentExchange==null) return@observe
                //ToastUtil.show("消耗${viewModel.currentExchange!!.goldNumber}金币，兑换vip会员${viewModel.currentExchange!!.norm}天")
                mGoldExchangeDialog?.dismiss()

                val dialog=GoldExchangeTipDialog(requireContext())
                dialog.setGoldSpend(viewModel.currentExchange!!.goldNumber)
                dialog.setObtainDay(viewModel.currentExchange!!.norm)
                dialog.show()

                showUserInfo()
            }
        }

        viewModel.todayGold.observe(this){data->
            databinding.mineTvTodayGold.text=data.toString()
        }

        viewModel.todayRead.observe(this){data->
            databinding.mineTvTodayRead.text=(data/60).toString()+"min"
        }
    }

    override fun initListData() {

    }

    override fun getRefreshLayout(): SmartRefreshLayout {
        return databinding.mineSrl
    }

    override fun getListAdapter(): RecyclerView.Adapter<BaseViewHolder>? {
        return null
    }

    private fun showGoldExchangeDialog(list: MutableList<GoldExchangeVipBean>){
        mGoldExchangeDialog=GoldExchangeDialog(requireContext(),list)
        mGoldExchangeDialog!!.setExchangeListener {p->
            viewModel.goldExchangeVip(p)
        }
        mGoldExchangeDialog!!.show()
    }

    private fun isShowMessageTip(msgCount:Int):Boolean{
        if(UserInfoManager.isLogin && UserInfoManager.userInfo!=null){
            //Judging the time of the latest message
            return TimeUtil.timeString2Stamp(UserInfoManager.userInfo!!.lookSystemMsgTime)<viewModel.lastMsgTime && msgCount>0
        }else{
            val lastReadSystemMsgTime= SharedPreferenceHelper.getInt("stytem_msg","last_read_time")
            return lastReadSystemMsgTime<viewModel.lastMsgTime/1000 && msgCount>0
        }
    }

    private fun showMessageTip(msgCount:Int){
        ViewHelper.setVisibility(isShowMessageTip(msgCount),databinding.mineMtvMessage)
    }

    override fun onResume() {
        super.onResume()
        showUserInfo()
        onGetData()
        initAdvert()
    }

    private fun initAdvert(){
        AdvertCoverHelper.loadAdvertByCover(requireActivity(),AdvertHelper.ADVERT_TYPE_BANNER,VarConfig.ADVERT_MINE_BANNER_INFO,
            databinding.mineFlAdvertBanner,0f,object :AdvertHelper.ILoadAdvertCommonListener{
                override fun onSuccess(type: Int, height: Int, view: View?) {
                    ViewHelper.setVisibility(true,databinding.mineFlAdvertBanner)
                    if(type == AdvertInfoBean.ADVERT_TYPE_CSJ){
                        databinding.mineFlAdvertBanner.removeAllViews()
                        databinding.mineFlAdvertBanner.addView(view)
                    }
                }

                override fun onError(type: Int, code: Int, msg: String) {
                    ViewHelper.setVisibility(false,databinding.mineFlAdvertBanner)
                    databinding.mineFlAdvertBanner.removeAllViews()
                }

                override fun onClose(type: Int) {
                    ViewHelper.setVisibility(false,databinding.mineFlAdvertBanner)
                    databinding.mineFlAdvertBanner.removeAllViews()
                }

            })
    }

    override fun isInitViewGetData(): Boolean {
        return false
    }

    private fun showUserInfo(){
        if(UserInfoManager.checkLogin()){
            ViewHelper.setVisibility(false, databinding.mineBtnLoginNow)
            if(FunctionConfig.IS_VIP_ENABLED){
                if(UserInfoManager.isVip()){
                    ViewHelper.setVisibility(true, databinding.mineIvUserVip,databinding.mineTvVipStatus)
                    ViewHelper.setVisibility(false, databinding.mineCclNotVip)
                    databinding.mineTvVipStatus.text="有效期至"+TimeUtil.formatTimeYYYYMMDD(UserInfoManager.vipValidateTime)
                }else{
                    ViewHelper.setVisibility(false, databinding.mineIvUserVip,databinding.mineTvVipStatus)
                    ViewHelper.setVisibility(true, databinding.mineCclNotVip)
                }
            }else{
                ViewHelper.setVisibility(false, databinding.mineTvVipStatus,databinding.mineCclNotVip,databinding.mineIvUserVip)
            }
            databinding.mineTvNickName.apply{
                text=UserInfoManager.userInfo!!.userNick
            }
            GlideUtil.loadNetImage(databinding.mineIvAvatar,UserInfoManager.userInfo!!.avatar)
            databinding.mineTvTotalGold.text=UserInfoManager.userInfo!!.gold.toString()
        }else{
            databinding.mineTvTotalGold.text="0"
            ViewHelper.setVisibility(true,databinding.mineBtnLoginNow)

            ViewHelper.setVisibility(false, databinding.mineTvVipStatus,databinding.mineCclNotVip,databinding.mineIvUserVip)

            databinding.mineTvNickName.apply {
                text = "游客"
            }
            Glide.with(requireContext()).load(com.songcha.library_business.R.mipmap.business_icon_avatar_nologin).into(databinding.mineIvAvatar)
        }

        viewModel.getTodayGold()
        viewModel.getTodayRead()

    }

    override fun onGetData() {
        viewModel.getSystemMessage()
        showUserInfo()
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe
    override fun onLoginSuccessEvent(event: LoginSuccessEvent) {

    }

    override fun isNeedShowLoadingDialog(): Boolean {
        return true
    }

    private fun onBookshelfOrGoldExchangeClick(){
        if(FunctionConfig.IS_VIP_ENABLED){
            if(UserInfoManager.checkJumpLogin()){
                if(viewModel.goldExchangeVipList.value==null){
                    showLoadingDialog()
                    viewModel.getGoldExchangeVipList()
                }else{
                    showGoldExchangeDialog(viewModel.goldExchangeVipList.value!!)
                }
            }
        }else{
            MainEventProxy.postToMyBookShelfEvent()
        }
    }

    private fun onNewMessageClick(){
        JumpUtil.toActivity(requireContext(),MessageActivity::class.java)
    }

    private fun onBrowseHistoryClick(){
        JumpUtil.toActivity(requireContext(),BrowseHistoryActivity::class.java)
    }

    private fun onContinueReadClick(){
        viewModel.continueRead()
    }

    private fun onFeedbackClick(){
        JumpUtil.toActivity(requireContext(),FeedbackActivity::class.java)
    }

    private fun onSettingClick(){
        JumpUtil.toActivity(requireContext(),SettingActivity::class.java)
    }

    override fun onClick(v: View?) {
        if(v==null) return
        when(v.id){
            R.id.mine_btn_login_now->{
                ARouter.getInstance().build("/login/LoginActivity").navigation()
            }
            R.id.mine_ll_user_top->{
                if(UserInfoManager.checkJumpLogin()){
                    JumpUtil.toActivity(v.context,UserInfoActivity::class.java)
                }
            }
            R.id.mine_ll_gold_exchange->{
                onBookshelfOrGoldExchangeClick()
            }
            R.id.mine_ll_msg->{
                onNewMessageClick()
            }
            R.id.mine_ll_browse_history->{
                onBrowseHistoryClick()
            }
            R.id.mine_ll_setting->{
                onSettingClick()
            }
            R.id.mine_ll_feedback->{
                onFeedbackClick()
            }
            R.id.mine_ll_continue_read->{
                onContinueReadClick()
            }
            R.id.mine_ccl_vip->{
                if(FunctionConfig.IS_VIP_ENABLED){
                    if(UserInfoManager.checkJumpLogin())
                        BusinessJumpUtil.toARouterActivity("/vip/VipRechargeActivity")
                }else{
                    ToastUtil.show("敬请期待")
                }
            }

        }
    }

    override fun onBottomNavigationItemChange(position: Int,tag:String) {
        if(tag==TAG){
            UMengHelper.onUMEvent(requireContext(),"bottom_tab_mine")
            showUserInfo()
        }
    }


}